package me.zhengjie.modules.web.service.course.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.config.entity.PageData;
import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.constant.ConstantUtils;
import me.zhengjie.modules.system.domain.StudentWitnessConfig;
import me.zhengjie.modules.system.domain.StudentWitnessLike;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.StudentWitnessConfigService;
import me.zhengjie.modules.system.service.StudentWitnessItemConfigService;
import me.zhengjie.modules.system.service.StudentWitnessLikeService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.service.mapstruct.StudentWitnessConfigPlusMapper;
import me.zhengjie.modules.web.domain.course.StudentWitnessCategoryResp;
import me.zhengjie.modules.web.domain.course.StudentWitnessListReq;
import me.zhengjie.modules.web.domain.course.StudentWitnessListResp;
import me.zhengjie.modules.web.service.course.IStudentWitnessService;
import me.zhengjie.modules.web.service.mybatisplus.IStudentWitnessConfigPlusService;
import me.zhengjie.request.ATMRContext;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 王宇
 */
@Service
public class StudentWitnessServiceImpl implements IStudentWitnessService {

    @Autowired
    private StudentWitnessLikeService likeService;

    @Autowired
    private DictDetailService dictDetailService;

    @Autowired
    private StudentWitnessConfigService configService;

    @Autowired
    private StudentWitnessItemConfigService itemConfigService;

    @Autowired
    private IStudentWitnessConfigPlusService configPlusService;

    @Autowired
    private StudentWitnessConfigPlusMapper configPlusMapper;

    @Override
    public boolean like(Long witnessId,String openId,boolean cancelLike) {
        if (StringUtils.isBlank(openId) || Objects.isNull(witnessId)){
            throw new WeChatException("缺少参数");
        }

        StudentWitnessLikeQueryCriteria criteria = new StudentWitnessLikeQueryCriteria();
        criteria.setOpenId(openId);
        criteria.setWitnessId(witnessId);
        List<StudentWitnessLikeDto> likeDtoList = likeService.queryAll(criteria);
        if (CollectionUtils.isNotEmpty(likeDtoList)){
            if (cancelLike){
                Long[] longs = {likeDtoList.get(0).getLikeId()} ;
                likeService.deleteAll(longs);
                return true;
            }
            throw new WeChatException("已点赞成功");
        }
        if (cancelLike){
            throw new WeChatException("未点赞没法取消哦");
        }
        StudentWitnessLike studentWitnessLike = new StudentWitnessLike();
        studentWitnessLike.setOpenId(openId);
        studentWitnessLike.setWitnessId(witnessId);
        studentWitnessLike.setCreateTime(DateUtil.TimestampNow());
        likeService.create(studentWitnessLike);
        return true;
    }

    @Override
    public List<StudentWitnessCategoryResp> categoryList() {
        List<DictDetailDto> student_witness = dictDetailService.getDictByName("student_witness");
        if (CollectionUtils.isEmpty(student_witness)){
            throw new WeChatException("学员认证字典不存在");
        }
        List<StudentWitnessCategoryResp> list = new ArrayList<>();
        student_witness.stream().forEach(s -> {
            StudentWitnessCategoryResp resp = new StudentWitnessCategoryResp();
            resp.setCategoryName(s.getLabel());
            resp.setCategoryId(Integer.parseInt(s.getValue()));
            list.add(resp);
        });
        return list;
    }


    @Override
    public List<StudentWitnessListResp> list(Integer categoryId) {
        if (Objects.isNull(categoryId)){
            throw new WeChatException("缺少参数");
        }
        StudentWitnessConfigQueryCriteria configQueryCriteria = new StudentWitnessConfigQueryCriteria();
        configQueryCriteria.setWitnessType(categoryId);
        configQueryCriteria.setWitnessStatus(ConstantUtils.Valid);
        List<StudentWitnessConfigDto> configDtoList = configService.queryAll(configQueryCriteria);
        if (CollectionUtils.isEmpty(configDtoList)){
            return null;
        }
        List<StudentWitnessListResp> list = new ArrayList<>();
        configDtoList.stream().forEach(s -> {
            StudentWitnessListResp resp = new StudentWitnessListResp();
            resp.setId(s.getWitnessId());
            StudentWitnessItemConfigQueryCriteria itemConfigQueryCriteria = new StudentWitnessItemConfigQueryCriteria();
            itemConfigQueryCriteria.setWitnessId(s.getWitnessId());
            List<StudentWitnessItemConfigDto> itemConfigDtoList = itemConfigService.queryAll(itemConfigQueryCriteria);
            if (CollectionUtils.isNotEmpty(itemConfigDtoList)){
                resp.setContent(itemConfigDtoList.stream().map(StudentWitnessItemConfigDto::getItemContent).collect(Collectors.toList()));
            }
            resp.setTitle(s.getTitle());
            resp.setStyle(s.getWitnessStyle());
            String timeStamp = DateUtil.getTimeStamp(s.getCreateTime());
            resp.setCreateTime(timeStamp);
            resp.setCreateDate(DateUtil.string2Date(timeStamp));
            StudentWitnessLikeQueryCriteria likeQueryCriteria = new StudentWitnessLikeQueryCriteria();
            likeQueryCriteria.setWitnessId(s.getWitnessId());
            List<StudentWitnessLikeDto> likeDtoList = likeService.queryAll(likeQueryCriteria);
            if (CollectionUtils.isNotEmpty(likeDtoList)){
                resp.setLikeNum(likeDtoList.size());
                if (likeDtoList.stream().anyMatch(dto -> dto.getOpenId().equals(ATMRContext.getContext().getOpenId()))) {
                    resp.setSelfLike(true);
                }
            }
            list.add(resp);
        });
        return list.stream().sorted(Comparator.comparing(StudentWitnessListResp::getCreateDate,Comparator.reverseOrder())).collect(Collectors.toList());
    }


    @Override
    public PageData<StudentWitnessListResp> listPage(StudentWitnessListReq request) {
        Page<StudentWitnessConfig> studentPage = Page.of(request.getPage(), request.getSize());
        LambdaQueryWrapper<StudentWitnessConfig> configWrapper = new LambdaQueryWrapper<>();
        configWrapper.eq(StudentWitnessConfig::getWitnessType,request.getCategoryId());
        configWrapper.eq(StudentWitnessConfig::getWitnessStatus,ConstantUtils.Valid);
        configWrapper.orderByDesc(StudentWitnessConfig::getCreateTime);
        Page<StudentWitnessConfig> configPage = configPlusMapper.selectPage(studentPage, configWrapper);
        if (Objects.isNull(configPage) || CollectionUtils.isEmpty(configPage.getRecords())){
            return null;
        }
        List<StudentWitnessListResp> list = new ArrayList<>();
        List<StudentWitnessConfig> records = configPage.getRecords();
        for (StudentWitnessConfig s : records) {
            StudentWitnessListResp resp = new StudentWitnessListResp();
            resp.setId(s.getWitnessId());
            StudentWitnessItemConfigQueryCriteria itemConfigQueryCriteria = new StudentWitnessItemConfigQueryCriteria();
            itemConfigQueryCriteria.setWitnessId(s.getWitnessId());
            List<StudentWitnessItemConfigDto> itemConfigDtoList = itemConfigService.queryAll(itemConfigQueryCriteria);
            if (CollectionUtils.isNotEmpty(itemConfigDtoList)){
                resp.setContent(itemConfigDtoList.stream().map(StudentWitnessItemConfigDto::getItemContent).collect(Collectors.toList()));
            }
            resp.setTitle(s.getTitle());
            resp.setStyle(s.getWitnessStyle());
            resp.setCreateTime(DateUtil.getTimeStamp(s.getCreateTime()));
            StudentWitnessLikeQueryCriteria likeQueryCriteria = new StudentWitnessLikeQueryCriteria();
            likeQueryCriteria.setWitnessId(s.getWitnessId());
            List<StudentWitnessLikeDto> likeDtoList = likeService.queryAll(likeQueryCriteria);
            if (CollectionUtils.isNotEmpty(likeDtoList)){
                resp.setLikeNum(likeDtoList.size());
                if (likeDtoList.stream().anyMatch(dto -> dto.getOpenId().equals(ATMRContext.getContext().getOpenId()))) {
                    resp.setSelfLike(true);
                }
            }
            list.add(resp);
        }
        return PageData.valueOf(list,configPage.getTotal(),configPage.getPages());
    }
}
